package connect2congress.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.http.client.*;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;

import com.google.gwt.widgetideas.graphics.client.GWTCanvas;
import connect2congress.client.legacy.Point;
import connect2congress.client.properties.Person;

import java.util.ArrayList;

/**
 * Entry point classes define <code>onModuleLoad()</code>
 */
public class Connect2Congress implements EntryPoint {

    public static final String URL_BASE = "http://www.connect2congress.com/rev5/";
    //public static final String URL_BASE = "http://127.0.0.1/rev5/";
    public static final String TICK_JSON_URL = URL_BASE + "getTicks.php?";
    public static final String WNOM_JSON_URL = URL_BASE + "getWnomScores.php?";
    public static final String VERB_JSON_URL = URL_BASE + "getVerbScores.php?";
    public static final String PEOPLE_JSON_URL = URL_BASE + "getPeople.php?";
    public static final String MAX_VERB = URL_BASE + "getMaxVerb.php?";



    private static int MAX_WINDOW_WIDTH = ((Integer)Window.getClientWidth()) - 10;
	private static int MAX_WINDOW_HEIGHT = ((Integer) Window.getClientHeight()) - 20;

    public static final int VERB_TYPE = 1;
    public static final int WNOM_TYPE = 0;

    public static final int HOUSE = 1;
    public static final int SENATE = 0;

    private AbsolutePanel timelinePanel = new AbsolutePanel();
    private HorizontalPanel senatePanel = new HorizontalPanel();
    private HorizontalPanel tooltipPanel = new HorizontalPanel();
    private TextBox tooltip = new TextBox();
    private Timeline timeline;

    private JsArray senators;
    private JsArray representatives;

    private ArrayList<Renderable> renders = new ArrayList<Renderable>();

    

    public void addToLoop(Renderable o) {
        renders.add(o);
    }

    public void setToolTip(String tip) {
        tooltip.setText(tip);
    }
    public void onModuleLoad() {
        System.out.println("Program Started");

        RootPanel.get("timeline").add(timelinePanel);
        timeline = new Timeline(new Point(0,0),new Point(100,MAX_WINDOW_HEIGHT),this);
        timelinePanel.add(timeline);
        //timelinePanel.setS
        loadSenators();
        //loadRepresentatives();

        RootPanel.get("senate").add(senatePanel);
        RootPanel.get("tooltip").add(tooltipPanel);
        tooltipPanel.add(tooltip);
        tooltip.setVisibleLength(100);

        timeline.addMouseDownHandler(new MouseDownHandler() {
            public void onMouseDown(MouseDownEvent event) {
                 int x = event.getNativeEvent().getClientX() - timeline.getAbsoluteLeft() + Window.getScrollLeft();
                 int y = event.getNativeEvent().getClientY() - timeline.getAbsoluteTop() + Window.getScrollTop();

                //System.out.println("Mouse Pressed on timeline at: " + event.getClientX() + " , " + event.getClientY());
				timeline.mousePressed(x,y);
            }
        });
        timeline.addMouseMoveHandler(new MouseMoveHandler() {
            public void onMouseMove(MouseMoveEvent event) {
                 int x = event.getNativeEvent().getClientX() - timeline.getAbsoluteLeft() + Window.getScrollLeft();
                 int y = event.getNativeEvent().getClientY() - timeline.getAbsoluteTop() + Window.getScrollTop();

               // System.out.println("Mouse Moved on timeline at: " + event.getClientX() + " , " + event.getClientY());
				timeline.mouseMoved(x,y);
            }


        });


        timeline.addMouseUpHandler(new MouseUpHandler() {
            public void onMouseUp(MouseUpEvent event) {
                 int x = event.getNativeEvent().getClientX() - timeline.getAbsoluteLeft() + Window.getScrollLeft();
                 int y = event.getNativeEvent().getClientY() - timeline.getAbsoluteTop() + Window.getScrollTop();

                //System.out.println("Mouse Up on timeline at: " + event.getClientX() + " , " + event.getClientY());
				timeline.mouseReleased(x,y);
            }
        });
        Timer timer = new Timer() {
            public void run() {
                for(int i = 0; i < renders.size(); i++) {
                    renders.get(i).renderingLoop();
                }
            }
        };
        timer.scheduleRepeating(1);

        Window.addResizeHandler(new ResizeHandler() {
           public void onResize(ResizeEvent re) {
               resized(re);
           }
        });

    }
    private void resized(ResizeEvent re) {
        MAX_WINDOW_WIDTH = ((Integer)Window.getClientWidth()) - 10;
	    MAX_WINDOW_HEIGHT = ((Integer) Window.getClientHeight()) - 20;

    }
    private void loadRepresentatives() {

        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, PEOPLE_JSON_URL + "chamber=" + HOUSE);

        try {
          Request request = builder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
              System.out.println("Couldn't retrieve JSON");
            }

            public void onResponseReceived(Request request, Response response) {
              if (200 == response.getStatusCode()) {
                System.out.println("Retrieved date info for timeline. Setting up timeline!");
                representatives = asArrayOfPeople(response.getText());
              } else {
                System.out.println("Couldn't retrieve JSON (" + response.getStatusCode()
                    + ")");
              }
            }
          });
        } catch (RequestException e) {
          System.out.println("Couldn't retrieve JSON");
        }
    }
    private void loadSenators() {

        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, PEOPLE_JSON_URL + "chamber=" + SENATE);

        try {
          Request request = builder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
              System.out.println("Couldn't retrieve JSON");
            }

            public void onResponseReceived(Request request, Response response) {
              if (200 == response.getStatusCode()) {
                System.out.println("Retrieved date info for timeline. Setting up timeline!");
                senators = asArrayOfPeople(response.getText());
                senatorsLoaded();

              } else {
                System.out.println("Couldn't retrieve JSON (" + response.getStatusCode()
                    + ")");
              }
            }
          });
        } catch (RequestException e) {
          System.out.println("Couldn't retrieve JSON");
        }

    }

    public void senatorsLoaded() {
        final Plot senate = new Plot(new Point(100,0),new Point(800,700),this, SENATE,senators);
        senatePanel.add(senate);
        timeline.addObserver(senate);

        senate.addMouseMoveHandler(new MouseMoveHandler() {
            public void onMouseMove(MouseMoveEvent event) {
                 int x = event.getNativeEvent().getClientX() - senate.getAbsoluteLeft() + Window.getScrollLeft();
                 int y = event.getNativeEvent().getClientY() - senate.getAbsoluteTop() + Window.getScrollTop();

               // System.out.println("Mouse Moved on timeline at: " + event.getClientX() + " , " + event.getClientY());
				senate.mouseMoved(x,y);
            }


        });
    }

    public Timeline getTimeline() {
        return timeline;
    }

/**
    * Convert the string of JSON into JavaScript object.
    */
    private final native JsArray<Person> asArrayOfPeople(String json) /*-{
        return eval(json);
    }-*/;


    //public void loadData(long dateA, long dateB) {
    //    System.out.println("Load requested for: " + dateA + " to " + dateB);
    //} 


}
